package com.pdool.gate.service;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pdool.common.constants.Constant;
import com.pdool.common.dict.BasePropVo;
import com.pdool.common.dict.CardInfoConfigVo;
import com.pdool.common.entity.CardGroupEntity;
import com.pdool.common.entity.CardInfoEntity;
import com.pdool.common.entity.RoleInfoEntity;
import com.pdool.common.mapper.impl.CardGroupDaoImpl;
import com.pdool.common.mapper.impl.CardInfoDaoImpl;
import com.pdool.common.mapper.impl.RoleInfoDaoImpl;
import com.pdool.common.mapper.mapper.WhiteMapper;
import com.pdool.gate.cache.dict.BasePropConfig;
import com.pdool.gate.cache.dict.CardConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
@Slf4j
public class RoleService implements ApplicationRunner {
    @Resource
    BasePropConfig basePropConfig;
    @Resource
    CardConfig cardConfig;
    @Resource
    RoleInfoDaoImpl roleInfoDao;

    @Autowired
    CardInfoDaoImpl cardInfoMapper;
    @Autowired
    CardGroupDaoImpl cardGroupMapper;
    @Autowired
    WhiteMapper whiteMapper;

    Set<Long> whiteSet;
    @Resource
    GmService gmService;
    public String roleLogin(String userName, String pwd) {
        long roleId = Long.parseLong(userName);
        if (!whiteSet.contains(roleId)) {
            throw new RuntimeException("本次未获得测试资格");
        }
       if (gmService.isInBlack(roleId)){
           throw new RuntimeException("本次未获得测试资格");
       }

        QueryWrapper<RoleInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId); //name不为空的用户

        String token;
        if (roleInfoDao.count(wrapper) == 0) {
            token = create(userName, "123", "head");
        } else {
            RoleInfoEntity RoleInfoEntity = roleInfoDao.getOne(wrapper);

            if (RoleInfoEntity == null) {
                throw new RuntimeException("本次未获得测试资格");
            }
            token = createToken(RoleInfoEntity, "login");
        }

        return token;
    }

    @Transactional
    public synchronized String create(String userName, String pwd, String head) {
        long roleId = Long.parseLong(userName);
        if (!whiteSet.contains(roleId)) {
            return "不是邀请测试用户";
        }
        QueryWrapper<RoleInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId); //name不为空的用户

        if (roleInfoDao.count(wrapper) > 0) {
            return "用户已创建";
        }
//        Integer maxRoleId = roleInfoDao.getBaseMapper().findMaxRoleId();
//        if (maxRoleId == null){
//            maxRoleId = 1;
//        }else {
//            maxRoleId +=1;
//        }
        Date date = new Date();
        RoleInfoEntity roleInfoEntity = new RoleInfoEntity();
        roleInfoEntity.setName("测试" + roleId);
        roleInfoEntity.setRoleId(roleId);
        roleInfoEntity.setPwd(pwd);
        roleInfoEntity.setRoleType(2);
        roleInfoEntity.setHead(head);
        roleInfoEntity.setCreateTime(date);
        roleInfoEntity.setUpdateTime(date);
        roleInfoDao.save(roleInfoEntity);

        BasePropVo cardGroupProp = basePropConfig.getByKey(Constant.PROP_INIT_CARD_GROUP);
        BasePropVo createRoleCardProp = basePropConfig.getByKey(Constant.PROP_CREATE_ROLE_CARD);

        String[] createRoleCardArr = createRoleCardProp.getValue().split(Constant.SPLIT_COMMA);
        ArrayList<CardInfoEntity> initCardList = new ArrayList<>();

        for (String s : createRoleCardArr) {
            int id = Integer.parseInt(s);
            CardInfoConfigVo byKey1 = cardConfig.getByKey(id);
            CardInfoEntity cardInfoEntity = new CardInfoEntity();
            cardInfoEntity.setCardId(id);
            cardInfoEntity.setRoleId(roleInfoEntity.getRoleId());
            cardInfoEntity.setLv(byKey1.getLv());
            initCardList.add(cardInfoEntity);
        }
        cardInfoMapper.saveBatch(initCardList);

        CardGroupEntity cardGroupEntity = new CardGroupEntity();
        cardGroupEntity.setRoleId(roleId);
        cardGroupEntity.setGroupIndex(Constant.DEFAULT_CARD_GROUP);
        cardGroupEntity.setCardGroup(cardGroupProp.getValue());
        cardGroupMapper.save(cardGroupEntity);

        String token = createToken(roleInfoEntity, "create");
        return token;
    }

    public String createToken(RoleInfoEntity RoleInfoEntity, String type) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("roleId", RoleInfoEntity.getRoleId());
        paramMap.put("type", type);
        paramMap.put("expire_time", System.currentTimeMillis() + 2 * 60 * 1000);
        String token = JWTUtil.createToken(paramMap, "key".getBytes());
        return token;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Set<Long> longs = new HashSet<>(whiteMapper.selectAllWhite());
        whiteSet = longs;
        log.error("加载白名单  {}",whiteSet.size());
    }
}
